package com.healthteches.read;

import de.beckhoff.jni.Convert;
import de.beckhoff.jni.JNIByteBuffer;
import de.beckhoff.jni.tcads.AdsCallDllFunction;
import de.beckhoff.jni.tcads.AmsAddr;

public class ReadString {
  public static void main(String[] args) {
    long nPort, nErr;
    AmsAddr addr = new AmsAddr();
    JNIByteBuffer dataBuff = new JNIByteBuffer(200);

    // Open communication
    nPort = AdsCallDllFunction.adsPortOpen();
    nErr = AdsCallDllFunction.getLocalAddress(addr);
    addr.setPort(801);
    if (nErr != 0) {
      System.out.println("Error: Open Communication: 0x" + Long.toHexString(nErr));
    }

    byte[] btSymName = "Main.strText".getBytes();
    JNIByteBuffer symbuff = new JNIByteBuffer(btSymName.length);
    symbuff.setByteArray(btSymName);
    final int buffsize = 256; // String
    JNIByteBuffer databuff = new JNIByteBuffer(buffsize);
    JNIByteBuffer hdlbuff = new JNIByteBuffer(4);
    nErr = 0;
    int symHandle = 0;

    // get handle by symbol name (symbol like "MAIN.iCounter" name in symbuff)
    nErr =
        AdsCallDllFunction.adsSyncReadWriteReq(
            addr,
            0xF003,
            0x0,
            hdlbuff.getUsedBytesCount(),
            hdlbuff, // buffer for getting handle
            symbuff.getUsedBytesCount(),
            symbuff); // buffer containg symbolpath
    byte[] byteArr = new byte[4];
    byteArr = hdlbuff.getByteArray();
    symHandle = Convert.ByteArrToInt(byteArr);

    // read variable by handle
    nErr =
        AdsCallDllFunction.adsSyncReadReq(
            addr, 0xF005, symHandle, databuff.getUsedBytesCount(), databuff);

    byte[] byteArr1 = new byte[buffsize];
    byteArr1 = databuff.getByteArray();
    String strVal = Convert.ByteArrToString(byteArr1);
    System.out.print(strVal);

    // Close communication
    nErr = AdsCallDllFunction.adsPortClose();
    if (nErr != 0) {
      System.out.println("Error: Close Communication: 0x" + Long.toHexString(nErr));
    }

    try {
      System.in.read();
    } catch (Exception e) {
      System.out.println("Error: Close program");
    }
  }
}
